/*******************************************************************************
 * Copyright (c) 2014 Steffen Mikkelsen
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Public License v3.0
 * which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/gpl.html
 * 
 * Contributors:
 *     Steffen Mikkelsen - initial API and implementation
 ******************************************************************************/
package com.subsecret.secureconnection.securestream.stream.obfuscation;

import java.io.IOException;
import java.io.OutputStream;

public class ObfuscationOutputStream extends OutputStream {
    
    private OutputStream os;
    private byte[] encryptionTable;
    
    public ObfuscationOutputStream(OutputStream os, byte[] secret) {
        this.os = os;
        encryptionTable = byteEncryptionTable(secret);
    }
    
    public static byte[] byteEncryptionTable(byte[] secret) {
        byte[] byteMapping = ObfuscationInputStream.getByteMapping(secret);
        return byteMapping;
    }
    
    @Override
    public void flush() throws IOException {
        os.flush();
    }
    
    private final byte[] singleByte = new byte[1];
    
    @Override
    public void write(int b) throws IOException {
        singleByte[0] = (byte) b;
        write(singleByte, 0, 1);
    }
    
    @Override
    public void write(byte b[]) throws IOException {
        write(b, 0, b.length);
    }
    
    @Override
    public void write(byte[] b, int off, int len) throws IOException {
        byte[] nb = new byte[len];
        for (int i = 0; i < len; i++) {
            nb[i] = (byte) encryptionTable[b[i + off] + 128];
        }
        os.write(nb);
    }
    
    @Override
    public void close() throws IOException {
        os.close();
    }
    
}
